package com.szf.task.web;

import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.szf.base.dao.Page;
import com.szf.base.exception.GenericException;
import com.szf.base.web.BaseActionSupport;
import com.szf.base.web.WebUtil;
import com.szf.task.entity.AppInfo;
import com.szf.task.service.AppService;
import com.szf.util.UuidGenerator;

@Namespace("/")
@Results({ @Result(name = "success", location = "/WEB-INF/jsp/task/app.jsp"), @Result(name = "input", location = "/WEB-INF/jsp/task/app-input.jsp") })
public class AppAction extends BaseActionSupport {
	private AppInfo app;
	@Autowired
	private AppService appService;

	@Override
	public String execute() {
		return super.execute();
	}

	public void list() {
		Page page = appService.queryByIbatis(warpRequest(request), "sinlog.listApp");
		WebUtil.renderJson(response, wrapResult(page));
	}

	public String add() {
		app = new AppInfo();
		app.setAppId(UuidGenerator.getUuid());
		app.setAccountId(principle.getAccountId());
		method = "add";
		return "input";
	}

	public String view() {
		app = appService.findById(app.getAppId());
		method = "view";
		return "input";
	}

	public String edit() {
		app = appService.findById(app.getAppId());
		method = "edit";
		return "input";
	}

	public void update() {
		try {
			if ("add".equals(method)) {
				AppInfo tmp = appService.findByKey(app.getAppKey());
				if (tmp != null) {
					throw new GenericException("KEY重复！");
				}
			}
			appService.save(app);
			ajaxDefaultResponse();
		} catch (Exception e) {
			ajaxErrorResponse(e.getMessage());
			logger.error(e.getMessage(), e);
		}
	}

	public void delete() {
		try {
			String ids = request.getParameter("ids");
			appService.deleteApp(ids);
			ajaxDefaultResponse();
		} catch (Exception e) {
			ajaxErrorResponse(e.getMessage());
			logger.error(e.getMessage(), e);
		}
	}

	public AppInfo getApp() {
		return app;
	}

	public void setApp(AppInfo app) {
		this.app = app;
	}

}
